<template>
  <div class="user-detail-container">
    <!-- 返回按钮 -->
    <el-card class="back-card" shadow="never">
      <el-button @click="handleBack">
        <IconifyIconOffline icon="ep:arrow-left" class="mr-1" />
        返回用户列表
      </el-button>
    </el-card>

    <!-- 用户基本信息 -->
    <el-card v-if="userDetail" class="info-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">用户信息</span>
          <el-tag :type="getStatusColor(userDetail.status)" size="large">
            {{ getStatusText(userDetail.status) }}
          </el-tag>
        </div>
      </template>

      <div class="user-info">
        <div class="user-avatar">
          <el-avatar :size="120" :src="userDetail.avatar">
            <IconifyIconOffline icon="ep:user" />
          </el-avatar>
        </div>
        <div class="user-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="用户名" :span="2">
              <el-text type="primary" size="large" tag="b">
                {{ userDetail.username }}
              </el-text>
            </el-descriptions-item>

            <el-descriptions-item label="真实姓名">
              {{ userDetail.realName || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ getGenderText(userDetail.gender) }}
            </el-descriptions-item>

            <el-descriptions-item label="手机号码">
              {{ userDetail.phone }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ userDetail.email || "-" }}
            </el-descriptions-item>

            <el-descriptions-item label="身份证号">
              {{ userDetail.idCard || "-" }}
            </el-descriptions-item>
            <el-descriptions-item label="出生日期">
              {{ formatDate(userDetail.birthday) || "-" }}
            </el-descriptions-item>

            <el-descriptions-item label="注册时间">
              {{ formatDateTime(userDetail.createTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="最后登录">
              {{ formatDateTime(userDetail.lastLoginTime) || "-" }}
            </el-descriptions-item>

            <el-descriptions-item label="用户类型">
              <el-tag :type="getTypeColor(userDetail.type)">
                {{ getTypeText(userDetail.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="认证状态">
              <el-tag :type="getVerifyColor(userDetail.verifyStatus)">
                {{ getVerifyText(userDetail.verifyStatus) }}
              </el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="地址" :span="2">
              {{ userDetail.address || "-" }}
            </el-descriptions-item>

            <el-descriptions-item label="个人简介" :span="2">
              {{ userDetail.bio || "-" }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 统计数据 -->
    <el-card class="stats-card" shadow="never">
      <template #header>
        <span class="card-title">数据统计</span>
      </template>

      <el-row :gutter="20">
        <el-col :span="6">
          <el-statistic title="登录次数" :value="statistics.loginCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="参与活动"
            :value="statistics.activities"
            suffix="次"
          />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="订单数量"
            :value="statistics.orders"
            suffix="个"
          />
        </el-col>
        <el-col :span="6">
          <el-statistic
            title="积分余额"
            :value="statistics.points"
            suffix="分"
          />
        </el-col>
      </el-row>
    </el-card>

    <!-- 角色权限 -->
    <el-card class="roles-card" shadow="never">
      <template #header>
        <div class="roles-header">
          <span class="card-title">角色权限</span>
          <el-button type="primary" @click="handleEditRoles">
            <IconifyIconOffline icon="ep:edit" class="mr-1" />
            编辑角色
          </el-button>
        </div>
      </template>

      <div class="roles-content">
        <div class="role-tags">
          <el-tag
            v-for="role in userRoles"
            :key="role.id"
            :type="getRoleColor(role.code)"
            size="large"
            class="role-tag"
          >
            {{ role.name }}
          </el-tag>
        </div>

        <el-divider content-position="left">权限列表</el-divider>

        <el-tree
          :data="permissionTree"
          show-checkbox
          node-key="id"
          :default-checked-keys="userPermissions"
          :props="{ children: 'children', label: 'name' }"
          class="permission-tree"
        />
      </div>
    </el-card>

    <!-- 活动记录 -->
    <el-card class="activities-card" shadow="never">
      <template #header>
        <span class="card-title">活动记录</span>
      </template>

      <el-table :data="activityList" stripe>
        <el-table-column prop="activityName" label="活动名称" />
        <el-table-column prop="type" label="活动类型">
          <template #default="{ row }">
            <el-tag :type="getActivityTypeColor(row.type)" size="small">
              {{ getActivityTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="参与状态">
          <template #default="{ row }">
            <el-tag :type="getParticipateStatusColor(row.status)" size="small">
              {{ getParticipateStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="参与时间">
          <template #default="{ row }">
            {{ formatDateTime(row.joinTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewActivity(row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="activityPagination.page"
          v-model:page-size="activityPagination.size"
          :total="activityPagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleActivitySizeChange"
          @current-change="handleActivityCurrentChange"
        />
      </div>
    </el-card>

    <!-- 登录日志 -->
    <el-card class="logs-card" shadow="never">
      <template #header>
        <span class="card-title">登录日志</span>
      </template>

      <el-table :data="loginLogs" stripe>
        <el-table-column prop="loginTime" label="登录时间">
          <template #default="{ row }">
            {{ formatDateTime(row.loginTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="登录IP" />
        <el-table-column prop="location" label="登录地点" />
        <el-table-column prop="device" label="设备信息" />
        <el-table-column prop="browser" label="浏览器" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag
              :type="row.status === 'success' ? 'success' : 'danger'"
              size="small"
            >
              {{ row.status === "success" ? "成功" : "失败" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 操作按钮 -->
    <el-card v-if="userDetail" class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleEdit">
          <IconifyIconOffline icon="ep:edit" class="mr-1" />
          编辑信息
        </el-button>

        <el-button
          v-if="userDetail.verifyStatus === 'pending'"
          type="success"
          @click="handleVerify"
        >
          <IconifyIconOffline icon="ep:check" class="mr-1" />
          通过认证
        </el-button>

        <el-button type="warning" @click="handleResetPassword">
          <IconifyIconOffline icon="ep:refresh" class="mr-1" />
          重置密码
        </el-button>

        <el-button
          v-if="userDetail.status === 'active'"
          type="warning"
          @click="handleSuspend"
        >
          <IconifyIconOffline icon="ep:warning" class="mr-1" />
          暂停用户
        </el-button>

        <el-button
          v-if="userDetail.status === 'suspended'"
          type="success"
          @click="handleActivate"
        >
          <IconifyIconOffline icon="ep:check" class="mr-1" />
          激活用户
        </el-button>

        <el-button type="danger" @click="handleDelete">
          <IconifyIconOffline icon="ep:delete" class="mr-1" />
          删除用户
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(false);
const userDetail = ref(null);

// 分页
const activityPagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 统计数据
const statistics = reactive({
  loginCount: 156,
  activities: 23,
  orders: 45,
  points: 1280
});

// 用户角色
const userRoles = ref([
  { id: 1, name: "普通用户", code: "user" },
  { id: 2, name: "VIP用户", code: "vip" }
]);

// 用户权限
const userPermissions = ref([1, 2, 3, 5, 6]);

// 权限树
const permissionTree = ref([
  {
    id: 1,
    name: "用户管理",
    children: [
      { id: 2, name: "查看用户" },
      { id: 3, name: "编辑用户" }
    ]
  },
  {
    id: 4,
    name: "活动管理",
    children: [
      { id: 5, name: "查看活动" },
      { id: 6, name: "参与活动" }
    ]
  }
]);

// 活动记录
const activityList = ref([
  {
    id: 1,
    activityName: "春季篮球赛",
    type: "competition",
    status: "completed",
    joinTime: "2024-01-15 14:30:00",
    score: 85
  },
  {
    id: 2,
    activityName: "编程培训",
    type: "training",
    status: "ongoing",
    joinTime: "2024-01-10 10:00:00",
    score: 92
  }
]);

// 登录日志
const loginLogs = ref([
  {
    id: 1,
    loginTime: "2024-01-20 09:30:00",
    ip: "192.168.1.100",
    location: "北京市朝阳区",
    device: "Windows 10",
    browser: "Chrome 120.0",
    status: "success"
  },
  {
    id: 2,
    loginTime: "2024-01-19 14:20:00",
    ip: "192.168.1.101",
    location: "北京市海淀区",
    device: "iPhone 15",
    browser: "Safari 17.0",
    status: "success"
  }
]);

// 模拟用户详情数据
const mockUserDetail = {
  id: 1,
  username: "zhangsan",
  realName: "张三",
  phone: "13800138001",
  email: "zhangsan@example.com",
  avatar:
    "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=male%20user%20avatar&image_size=square",
  gender: "male",
  birthday: "1990-05-15",
  idCard: "110101199005150001",
  address: "北京市朝阳区某某街道123号",
  bio: "热爱运动，喜欢篮球和编程",
  type: "vip",
  status: "active",
  verifyStatus: "verified",
  createTime: "2023-01-15 10:30:00",
  lastLoginTime: "2024-01-20 09:30:00"
};

// 格式化日期
const formatDate = (date: string) => {
  return date ? dayjs(date).format("YYYY-MM-DD") : "";
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dateTime ? dayjs(dateTime).format("YYYY-MM-DD HH:mm:ss") : "";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    active: "正常",
    suspended: "暂停",
    deleted: "已删除"
  };
  return statusMap[status] || status;
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    active: "success",
    suspended: "warning",
    deleted: "danger"
  };
  return colorMap[status] || "info";
};

// 获取性别文本
const getGenderText = (gender: string) => {
  const genderMap: Record<string, string> = {
    male: "男",
    female: "女",
    unknown: "未知"
  };
  return genderMap[gender] || "未知";
};

// 获取用户类型文本
const getTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    normal: "普通用户",
    vip: "VIP用户",
    admin: "管理员"
  };
  return typeMap[type] || type;
};

// 获取用户类型颜色
const getTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    normal: "info",
    vip: "warning",
    admin: "danger"
  };
  return colorMap[type] || "info";
};

// 获取认证状态文本
const getVerifyText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: "待认证",
    verified: "已认证",
    rejected: "认证失败"
  };
  return statusMap[status] || status;
};

// 获取认证状态颜色
const getVerifyColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: "warning",
    verified: "success",
    rejected: "danger"
  };
  return colorMap[status] || "info";
};

// 获取角色颜色
const getRoleColor = (code: string) => {
  const colorMap: Record<string, string> = {
    admin: "danger",
    vip: "warning",
    user: "primary"
  };
  return colorMap[code] || "info";
};

// 获取活动类型文本
const getActivityTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    competition: "比赛",
    training: "培训",
    meeting: "会议",
    social: "社交"
  };
  return typeMap[type] || type;
};

// 获取活动类型颜色
const getActivityTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    competition: "success",
    training: "primary",
    meeting: "warning",
    social: "info"
  };
  return colorMap[type] || "info";
};

// 获取参与状态文本
const getParticipateStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    completed: "已完成",
    ongoing: "进行中",
    cancelled: "已取消"
  };
  return statusMap[status] || status;
};

// 获取参与状态颜色
const getParticipateStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    completed: "success",
    ongoing: "primary",
    cancelled: "danger"
  };
  return colorMap[status] || "info";
};

// 返回列表
const handleBack = () => {
  router.push("/user/list");
};

// 编辑信息
const handleEdit = () => {
  ElMessage.info("编辑功能开发中");
};

// 编辑角色
const handleEditRoles = () => {
  ElMessage.info("编辑角色功能开发中");
};

// 通过认证
const handleVerify = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要通过 "${userDetail.value?.realName || userDetail.value?.username}" 的认证申请吗？`,
      "确认认证",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    if (userDetail.value) {
      userDetail.value.verifyStatus = "verified";
    }
    ElMessage.success("认证通过");
  } catch {
    // 用户取消
  }
};

// 重置密码
const handleResetPassword = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要重置 "${userDetail.value?.realName || userDetail.value?.username}" 的密码吗？`,
      "确认重置",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    ElMessage.success("密码已重置，新密码已发送到用户邮箱");
  } catch {
    // 用户取消
  }
};

// 暂停用户
const handleSuspend = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要暂停 "${userDetail.value?.realName || userDetail.value?.username}" 吗？`,
      "确认暂停",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    if (userDetail.value) {
      userDetail.value.status = "suspended";
    }
    ElMessage.success("用户已暂停");
  } catch {
    // 用户取消
  }
};

// 激活用户
const handleActivate = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要激活 "${userDetail.value?.realName || userDetail.value?.username}" 吗？`,
      "确认激活",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "success"
      }
    );

    if (userDetail.value) {
      userDetail.value.status = "active";
    }
    ElMessage.success("用户已激活");
  } catch {
    // 用户取消
  }
};

// 删除用户
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 "${userDetail.value?.realName || userDetail.value?.username}" 吗？此操作不可恢复！`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "danger"
      }
    );

    ElMessage.success("用户已删除");
    router.push("/user/list");
  } catch {
    // 用户取消
  }
};

// 查看活动详情
const handleViewActivity = (row: any) => {
  ElMessage.info(`查看活动：${row.activityName}`);
};

// 活动分页变化
const handleActivitySizeChange = (size: number) => {
  activityPagination.size = size;
  loadActivityList();
};

const handleActivityCurrentChange = (page: number) => {
  activityPagination.page = page;
  loadActivityList();
};

// 加载用户详情
const loadUserDetail = async () => {
  loading.value = true;
  try {
    const userId = route.params.id;
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    userDetail.value = mockUserDetail;
  } catch (error) {
    ElMessage.error("加载用户详情失败");
  } finally {
    loading.value = false;
  }
};

// 加载活动列表
const loadActivityList = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300));
    activityPagination.total = activityList.value.length;
  } catch (error) {
    ElMessage.error("加载活动列表失败");
  }
};

onMounted(() => {
  loadUserDetail();
  loadActivityList();
});
</script>

<style scoped lang="scss">
.user-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.back-card,
.info-card,
.stats-card,
.roles-card,
.activities-card,
.logs-card,
.action-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .card-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.user-info {
  display: flex;
  gap: 20px;
  align-items: flex-start;

  .user-avatar {
    flex-shrink: 0;
  }

  .user-content {
    flex: 1;
  }
}

.roles-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.roles-content {
  .role-tags {
    margin-bottom: 20px;

    .role-tag {
      margin-right: 8px;
      margin-bottom: 8px;
    }
  }

  .permission-tree {
    max-height: 300px;
    overflow-y: auto;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

@media (max-width: 768px) {
  .user-detail-container {
    padding: 10px;
  }

  .user-info {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .roles-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>
